// pages/confirm-order/confirm-order.js

const globalData = getApp().globalData

Page({

    /**
     * 页面的初始数据
     */
    data: {
        selectedFoodList: [],
        receiveInfo: {
            receivePerson: '',
            phoneNumber: '',
            receiveAddress: ''
        },
        allFoodPrice: 0,
        orderOrigin: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('goConfirmOrder', data => {
            this.setData({ selectedFoodList: data.selectedFoodList })
            this.data.orderOrigin = data.orderOrigin
            const totalPrices = this.data.selectedFoodList.map(item => item.totalPrice)
            const allFoodPrice = totalPrices.reduce(
                (total, num) => {
                    return total + num
                },
                0
            )
            this.setData({ allFoodPrice })
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    collectReceiveInfo (event) {
        const { type } = event.currentTarget.dataset
        this.setData({ [`receiveInfo.${type}`]: event.detail.value })
    },

    showMessage (message) {
        wx.showToast({
            title: message,
            icon: 'none',
            mask: true
        })
    },

    onPay () {
        if (!this.data.receiveInfo.receivePerson.trim()) {
            this.showMessage('请填写收货人')
            return
        }
        if (!(/^1[3456789]\d{9}$/.test(this.data.receiveInfo.phoneNumber))) {
            this.showMessage('请填写正确格式的手机号码')
            return
        }
        if (!this.data.receiveInfo.receiveAddress.trim()) {
            this.showMessage('请填写收货地址')
            return
        }
        const order = {
            orderId: globalData.orderList.length + 1,
            orderStatus: 1,
            foodList: this.data.selectedFoodList,
            orderTotalPrice: this.data.allFoodPrice,
            receiveInfo: this.data.receiveInfo
        }
        globalData.orderList.push(order)
        if (this.data.orderOrigin === 'shoppingCart') {
            globalData.shoppingCartList = []
        }
        this.showMessage('暂不支持支付功能')
        setTimeout(() => {
            wx.navigateBack()
        }, 1000)
    }
})